<?php

namespace App\Modules\Admin\Services;

use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Rabc\AdminMenu;
use App\Modules\Admin\Entities\Rabc\AdminRole;
use Illuminate\Support\Facades\DB;

class AdminRoleService extends BaseService
{
    public function __construct(AdminRole $adminRole)
    {
        $this->model = $adminRole;
        $this->with = ['menus'];
    }

    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $query->where('role_name', 'LIKE', '%' . trim($search) . '%');
            }
            // 状态
            $is_check = $request->input('is_check', -1);
            if ($is_check > -1){
                $query->where('is_check', '=', $is_check);
            }
        };
        return parent::lists($params); // TODO: Change the autogenerated stub
    }

    public function getSelectLists($request)
    {
        return $this->model->where(function($query) use ($request){
            $search = $request->input('search', '');
            // 可以按照名称进行搜索
            if (!empty($search)){
                $query->where('role_name', 'LIKE', '%' . trim($search) . '%');
            }
        })->where('is_check', 1)->select(['role_id', 'role_name', 'role_remarks'])->orderBy($this->model->getKeyName(), 'ASC')->limit(100)->get();
    }

    public function create(array $params)
    {
        DB::beginTransaction();
        try{
            parent::create($params); // TODO: Change the autogenerated stub

            $this->setMenuForRole($params);

            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }

    public function update(array $params)
    {
        DB::beginTransaction();
        try{
            parent::update($params); // TODO: Change the autogenerated stub

            $this->setMenuForRole($params);

            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }

    protected function setMenuForRole($params)
    {
        // 超级管理员角色不可编辑
        if (isset($params['menu_ids']) && $this->detail->{$this->model->getKeyName()} != 1){
            $menu_rules = $params['menu_ids'];

            $all_menus = AdminMenu::select('menu_id')->find($menu_rules)->toArray();//当前选中的菜单权限
            $new_all_menus = array_column($all_menus, 'menu_id', 'menu_id');
            $has_menus = $this->detail->menus->toArray();//当前已有的菜单权限
            $new_has_menus = array_column($has_menus, 'menu_id', 'menu_id');

            $primary_key = $this->model->getKeyName();
            /**
             * 添加的权限
             */
            $add_menus = get_array_diff($new_all_menus, $new_has_menus);
            if (!empty($add_menus)) {
                foreach ($add_menus as $menus) $this->model->grantMenus([
                    $primary_key => $this->detail->{$primary_key},
                    'menu_id' => $menus,
                ]);
            }

            /**
             * 要删除的权限
             */
            $delete_menus = get_array_diff($new_has_menus, $new_all_menus);
            if (!empty($delete_menus)) {
                foreach ($delete_menus as $menus) $this->model->deleteMenus([
                    $primary_key => $this->detail->{$primary_key},
                    'menu_id' => $menus,
                ]);
            }
        }
    }

    public function delete(array $params)
    {
        $primaryKey = $this->model->getKeyName();
        if (isset($params[$primaryKey]) && $params[$primaryKey] == 1){
            throw new Exception('超管角色禁止删除！');
        }

        // 如果是批量删除，那么移除Id
        if(isset($params['is_batch']) && $params['is_batch'] == 1){
            $ids_ary = explode(',', $params[$primaryKey]);
            if (in_array(1, $ids_ary)){
                $key = array_search(1, $ids_ary);
                unset($ids_ary[$key]);
                $params[$primaryKey] = implode(',', $ids_ary);
            }
        }
        return parent::delete($params); // TODO: Change the autogenerated stub
    }
}
